package xin.alum.aim.redis;

import xin.alum.aim.groups.SessionGroups;
import xin.alum.aim.model.Notice;
import xin.alum.aim.util.JSONUtils;
import com.fasterxml.jackson.core.type.TypeReference;
import org.springframework.data.redis.connection.MessageListener;


/**
 * 集群环境下，监听redis队列，广播消息到每个实例进行推送
 * 如果使用MQ的情况也，最好替换为MQ消息队列
 */
class PushMessageListener implements MessageListener {

    private final SessionGroups groups;

    PushMessageListener(SessionGroups groups) {
        this.groups = groups;
    }

    @Override
    public void onMessage(org.springframework.data.redis.connection.Message redisMessage, byte[] bytes) {
        Notice notice = JSONUtils.fromJson(redisMessage.getBody(), new TypeReference<Notice>() {
        });
        groups.get(notice.getRecipient()).sends(notice);
    }
}
